package myapps.ttclient.activity;

import myapps.ttclient.GlobalVariables;
import myapps.ttclient.R;
import myapps.ttclient.app.TTClientApplication;
import myapps.ttclient.asymmetric_encryption.RSA;
import myapps.ttclient.asymmetric_encryption.RSAKey;
import myapps.ttclient.asymmetric_encryption.RSAKeyManager;
import myapps.ttclient.baseclass_and_interface.TTConnectionStateChangedListener;
import myapps.ttclient.baseclass_and_interface.TTClientConnection;
import myapps.ttclient.baseclass_and_interface.TTClientMessage;
import myapps.ttclient.baseclass_and_interface.TTClientMessageReceiver;
import myapps.ttclient.connection.Connection;
import myapps.ttclient.connection.ConnectionListManager;
import myapps.ttclient.connection.Connection_Bluetooth;
import myapps.ttclient.connection.Connection_Wifi;
import myapps.ttclient.protocol.message.SignOutRequestMessage;
import myapps.ttclient.protocol.message.SignOutResponseMessage;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainMenuActivity extends Activity implements OnClickListener, 
TTConnectionStateChangedListener, TTClientMessageReceiver {

	public final static int MENUITEM_OPTIONS = 1;
	public final static int MENUITEM_HELP = 2;
	public final static int MENUITEM_ABOUT = 3;
	public final static int MENUITEM_EXIT = 4;

	private TTClientApplication application;

	private ConnectionListManager connectionListManager;

	private TextView tvConnectionName;
	private TextView tvCurrentStatus;

	private TextView tvCurrentAuthority;

	private Button btn_ConnectionSettings_Manage; 
	private Button btn_ConnectionSettings_Connnect; 
	private Button btn_ConnectionSettings_Disconnect; 

	private Button btn_Authentication_SignIn;
	private Button btn_Authentication_SignOut;

	private Button btn_MainAction_Pick;

	private Button btn_DeletePrivateData_Enter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.application = (TTClientApplication) this.getApplication();

		this.connectionListManager = this.application.getConnectionListManager();

		setContentView(R.layout.mainmenu);

		tvConnectionName = (TextView) findViewById(R.id.tvConnectionName);
		tvCurrentStatus = (TextView) findViewById(R.id.tvCurrentStatus);

		tvCurrentAuthority = (TextView) findViewById(R.id.tvCurrentAuthority);

		btn_ConnectionSettings_Manage = (Button) findViewById(R.id.btn_ConnectionSettings_Manage);
		btn_ConnectionSettings_Connnect = (Button) findViewById(R.id.btn_ConnectionSettings_Connect);
		btn_ConnectionSettings_Disconnect = (Button) findViewById(R.id.btn_ConnectionSettings_Disconnect);
		btn_Authentication_SignIn = (Button) findViewById(R.id.btn_Authentication_SignIn);
		btn_Authentication_SignOut = (Button) findViewById(R.id.btn_Authentication_SignOut);
		btn_MainAction_Pick = (Button) findViewById(R.id.btn_MainActions_Pick);
		btn_DeletePrivateData_Enter = (Button) findViewById(R.id.btn_DeletePrivateData_Enter);

		btn_ConnectionSettings_Manage.setOnClickListener(this);
		btn_ConnectionSettings_Connnect.setOnClickListener(this);
		btn_ConnectionSettings_Disconnect.setOnClickListener(this);
		btn_Authentication_SignIn.setOnClickListener(this);
		btn_Authentication_SignOut.setOnClickListener(this);
		btn_MainAction_Pick.setOnClickListener(this);
		btn_DeletePrivateData_Enter.setOnClickListener(this);

		refreshState();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		int groupId = 0; 

		//arguments: groupId, optionId, order, title
		MenuItem item1 = menu.add(groupId, MENUITEM_OPTIONS, 1, "Options");
		MenuItem item2 = menu.add(groupId, MENUITEM_HELP, 2, "Help");
		MenuItem item3 = menu.add(groupId, MENUITEM_ABOUT, 3, "About");
		MenuItem item4 = menu.add(groupId, MENUITEM_EXIT, 4, "Exit");

		item1.setIcon(R.drawable.ic_menu_preferences);
		item2.setIcon(R.drawable.ic_menu_help);
		item3.setIcon(R.drawable.ic_menu_info_details);
		item4.setIcon(R.drawable.ic_menu_close_clear_cancel);

		return super.onCreateOptionsMenu(menu);
	}

	private void Test() {
		try {
			String key = "asdfghjk";

			byte[] dataToBeEncrypted = key.getBytes("UTF-16LE");

			RSAKey publicKey = RSAKeyManager.getInstance().get_clientPublicKey();
			RSAKey privateKey = RSAKeyManager.getInstance().get_clientPrivateKey();

			byte[] encryptedData = RSA.rsaEncryptWithPublicKey(publicKey, dataToBeEncrypted);

			byte[] decryptedData = RSA.rsaDecryptWithPrivateKey(privateKey, encryptedData);

			byte[] temp = decryptedData;

		} catch (Exception e) {

		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return (applyMenuOption(item) || super.onOptionsItemSelected(item));
	}

	private boolean applyMenuOption(MenuItem item) {
		int menuItemId = item.getItemId();

		switch (menuItemId) {
		case MENUITEM_OPTIONS:
			on_Options();
			break;

		case MENUITEM_HELP:
			on_Help();
			break;

		case MENUITEM_ABOUT:
			on_About();
			break;

		case MENUITEM_EXIT:
			on_Exit();
			break;

		default:
			break;
		}

		return false;
	}

	private void on_Options() {
		this.startActivity(new Intent(this, OptionsActivity.class));
	}

	private void on_Help() {
		this.startActivity(new Intent(this, HelpActivity.class));
	}

	private void on_About() {
		this.startActivity(new Intent(this, AboutActivity.class));
	}

	private void on_Exit() {
		AlertDialog myQuittingDialogBox = new AlertDialog.Builder(this)
		.setTitle("Terminator")
		.setMessage("Are you sure that you want to quit?")
		.setIcon(R.drawable.ic_menu_end_conversation)
		.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int whichButton) {
				MainMenuActivity.this.finish();
			}
		})
		.setNegativeButton("No", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int whichButton) {

			}
		})
		.create();

		myQuittingDialogBox.show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			this.finish();
			return false;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == btn_ConnectionSettings_Manage.getId())	{
			on_btn_ConnectionSettings_Manage_Clicked(v);

		} else if(v.getId() == btn_ConnectionSettings_Connnect.getId())	{
			on_btn_ConnectionSettings_Connnect_Clicked(v);

		} else if(v.getId() == btn_ConnectionSettings_Disconnect.getId()) {
			on_btn_ConnectionSettings_Disconnect_Clicked(v);

		} else if(v.getId() == btn_Authentication_SignIn.getId()) {
			on_btn_Authentication_SignIn_Clicked(v);

		} else if(v.getId() == btn_Authentication_SignOut.getId()) {
			on_btn_Authentication_SignOut_Clicked(v);

		} else if(v.getId() == btn_MainAction_Pick.getId())	{
			on_btn_MainAction_Pick_Clicked(v);

		} else if(v.getId() == btn_DeletePrivateData_Enter.getId())	{
			on_btn_DeletePrivateData_Enter_Clicked(v);

		} 
	}

	private void on_btn_ConnectionSettings_Manage_Clicked(View v) {
		Intent connection_settings_activity = new Intent(this, 
				ConnectionSettingsActivity.class);
		startActivity(connection_settings_activity);
	}

	private void on_btn_ConnectionSettings_Connnect_Clicked(View v) {
		this.application.connect();
	}

	private void on_btn_ConnectionSettings_Disconnect_Clicked(View v) {
		this.application.disconnect();
	}

	private void on_btn_Authentication_SignIn_Clicked(View v) {
		Intent authentication_activity = new Intent(this, 
				AuthenticationSignInActivity.class);
		startActivity(authentication_activity);
	}

	private void on_btn_Authentication_SignOut_Clicked(View v) {
		(new AlertDialog.Builder(this))
		.setTitle("Confirming Dialog")
		.setMessage("Are you sure?")
		.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				MainMenuActivity.this.application.sendMessage(new SignOutRequestMessage(GlobalVariables.getTemporaryKey()));
				//MainMenuActivity.this.application.showToast("The Client has sent a request to the server.");
			}
		})
		.setNegativeButton("No", null).show();
	}

	private void on_btn_MainAction_Pick_Clicked(View v) {
		this.startActivity(new Intent(this, MainActionsActivity.class));
	}

	private void on_btn_DeletePrivateData_Enter_Clicked(View v) {
		this.startActivity(new Intent(this, DeletePrivateDataActivity.class));
	}

	private void setGuestSettings() {
		GlobalVariables.setCurrrentAuthority(GlobalVariables.AUTHORITY_GUEST);
		GlobalVariables.setTemporaryKey("");

		btn_Authentication_SignIn.setEnabled(true);
		btn_Authentication_SignOut.setEnabled(false);
	}

	@Override
	protected void onResume() {
		refreshState();

		this.application.registerMessageReceiver(this);
		this.application.registerConnectionStateChangedListener(this);
		
		this.refreshState();

		super.onResume();
	}

	@Override
	protected void onPause() {
		this.application.unregisterConnectionStateChangedListener(this);
		this.application.registerMessageReceiver(this);
		super.onPause();
	}
	
	@Override
	public void onConnectionStateChanged() {
		refreshState();
	}

	@Override
	protected void onDestroy() {
		this.application.disconnect();
		super.onDestroy();
	}

	private void refreshState() {
		/////////////////////////////////////////////////////////////////////
		String text = "N/A";

		Connection  connection = this.connectionListManager.getUsed();

		if(connection != null) {
			if(connection instanceof Connection_Wifi) {
				text = connection.getName() + " (Wifi)";

			} else if (connection instanceof Connection_Bluetooth) {
				text = connection.getName() + " (Bluetooth)";
			}
		}

		tvConnectionName.setText(text);
		//////////////////////////////////////////////////////////////////////

		TTClientConnection clientConnection = this.application.getConnection();
		if(clientConnection != null) {
			tvCurrentStatus.setText("Connected");
			btn_ConnectionSettings_Connnect.setEnabled(false);
			btn_ConnectionSettings_Disconnect.setEnabled(true);

			this.refreshScreenContent_2();

			btn_MainAction_Pick.setEnabled(true);

		} else {
			tvCurrentStatus.setText("Not connected");
			btn_ConnectionSettings_Connnect.setEnabled(true);
			btn_ConnectionSettings_Disconnect.setEnabled(false);

			btn_Authentication_SignIn.setEnabled(false);
			btn_Authentication_SignOut.setEnabled(false);

			
			btn_MainAction_Pick.setEnabled(false);
			
		}
	}

	private void refreshScreenContent_2() {
		int curAuthority = GlobalVariables.getCurrentAuthority();

		if(curAuthority == GlobalVariables.AUTHORITY_ADMIN) {
			tvCurrentAuthority.setText("Admin");
			btn_Authentication_SignIn.setEnabled(false);
			btn_Authentication_SignOut.setEnabled(true);
		} else if(curAuthority == GlobalVariables.AUTHORITY_KEY_MEMBER) {
			tvCurrentAuthority.setText("Key member");
			btn_Authentication_SignIn.setEnabled(false);
			btn_Authentication_SignOut.setEnabled(true);
		}  else if(curAuthority == GlobalVariables.AUTHORITY_MEMBER) {
			tvCurrentAuthority.setText("Member");
			btn_Authentication_SignIn.setEnabled(false);
			btn_Authentication_SignOut.setEnabled(true);
		} else if (curAuthority == GlobalVariables.AUTHORITY_GUEST)	{
			tvCurrentAuthority.setText("Guest");
			btn_Authentication_SignIn.setEnabled(true);
			btn_Authentication_SignOut.setEnabled(false);
		}
	}

	@Override
	public void receiveMessage(TTClientMessage message) {
		if(message instanceof SignOutResponseMessage) {
			if(((SignOutResponseMessage) message).result == true) {
				GlobalVariables.setCurrrentAuthority(GlobalVariables.AUTHORITY_GUEST);
				GlobalVariables.setTemporaryKey("");

				this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						MainMenuActivity.this.refreshScreenContent_2();
					}
				});

				this.application.showToast("Signed out successfully");
			} else {
				this.application.showToast(( (SignOutResponseMessage) message).text);
			}
		}
	}
}
